package cn.aopmin.java.api.lang;

/**
 * 线程安全问题之可见性问题
 * @author 白豆五
 * @since 2025/1/30
 */
public class ThreadSafeVisibilityTest {
    public static void main(String[] args) {
        ThreadSafeVisibility threadSafeVisibility = new ThreadSafeVisibility();
        Thread thread1 = new Thread(threadSafeVisibility,"线程1");
        thread1.start();


        /**
         * 期望结果：主线程的死循环结束
         * 实际结果：不会结束主线程的死循环
         */
        while (true){
            if (threadSafeVisibility.flag==true){
                System.out.println("主线程的死循环结束");
                break;
            }
        }
    }
}


class ThreadSafeVisibility implements Runnable{

    static volatile boolean flag = false;

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        try {
            System.out.println(name+"即将睡5秒钟...");
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        flag = true;
        System.out.println(name+"将flag值改成了"+flag);
    }
}